﻿using Prism.Commands;
using Prism.Mvvm;
using Sharp.Infrastructure.Network;
using StockTools.Configuration;
using StockTools.Model;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Net;
using System.Text;
using System.Threading.Tasks;

namespace StockTools.ViewModel
{
    public class CostCalculationViewModel : BindableBase
    {
        private ObservableCollection<SettingConfig.StockItem> stockData;
        public CostCalculationViewModel()
        {
            this.StockInfo = new Model.StockInfoModel();
            this.RateSetting = new Model.RateSettingModel();
            this.BuyingData = new Model.BuyingDataModel();
            this.SellingResult = new Model.SellingResultModel();
            this.Consult = new ConsultModel();
            this.StockData = new ObservableCollection<SettingConfig.StockItem>();

            GetCalculateItCommand = new DelegateCommand(ExecuteGetCalculateItCommand);

            LoadSettingConfig();


        }
        #region 属性


        /// <summary>
        /// 股票信息
        /// </summary>
        public StockInfoModel StockInfo { get; set; }
        /// <summary>
        /// 设置信息
        /// </summary>
        public RateSettingModel RateSetting { get; set; }
        /// <summary>
        /// 买入数据
        /// </summary>
        public BuyingDataModel BuyingData { get; set; }

        public ConsultModel Consult { get; internal set; }
        /// <summary>
        /// 卖出结果
        /// </summary>
        public SellingResultModel SellingResult { get; set; }



        public ObservableCollection<SettingConfig.StockItem> StockData { get => stockData; set => SetProperty(ref stockData, value); }

        #endregion

        private void LoadSettingConfig()
        {
            var settingConfig = SystemConfigManage.Read<SettingConfig>();

            this.RateSetting.Read(settingConfig);
            this.StockInfo.Code = settingConfig.Code;
            this.BuyingData.Code = settingConfig.Code;
            this.StockData.AddRange(settingConfig.StockData?.ToArray());
        }

        public Task getStockBaseInfo(string code = "")
        {
            return Task.Run(() =>
              {
                  //Thread.Sleep(5000);
                  string url = "";

                  var exchangeCode = "";
                  if (code.IsNullOrEmpty())
                  {
                      var config = SystemConfigManage.Read<SettingConfig>();
                      if (config.Code.IsNullOrEmpty())
                      {
                          return;
                      }
                      code = config.Code;
                  }

                  if (code.StartsWith("00") || code.StartsWith("3"))
                  {
                      exchangeCode = "sz";
                  }
                  else if (code.StartsWith("6"))
                  {
                      exchangeCode = "sh";
                  }
                  url = $"http://qt.gtimg.cn/q=s_{exchangeCode}{code}";

                  var net = new NetHelper();

                  Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
                  var res = net.Get(url);
                  if (res.StatusCode == HttpStatusCode.OK)
                  {
                      var data = res.Html.Split('~');
                      if (data.Length < 2) return;


                      this.StockInfo.Name = data[1];
                      this.StockInfo.Code = data[2];
                      if (this.StockInfo.Code.StartsWith("00") || this.StockInfo.Code.StartsWith("3"))
                      {
                          this.StockInfo.ExchangeName = "深交所";
                      }
                      else if (this.StockInfo.Code.StartsWith("6"))
                      {
                          this.StockInfo.ExchangeName = "沪交所";
                      }
                      this.StockInfo.LatestPrice = decimal.Parse(data[3]);

                      this.StockInfo.LatestPriceText = $"{this.StockInfo.LatestPrice}（{data[5]}%）";

                      this.StockInfo.OpeningPrice = this.StockInfo.LatestPrice - decimal.Parse(data[4]);

                      this.Consult.Compute(this.StockInfo.OpeningPrice);
                  }
                  else
                  {
                      this.Consult.Clear();
                  }


              });
        }

        public DelegateCommand GetCalculateItCommand { get; set; }


        void ExecuteGetCalculateItCommand()
        {
            this.BuyingData.Compute(RateSetting);

            this.SellingResult.Compute(BuyingData, RateSetting);
        }

     
    }
}
